package com.k.ums.security.handler;

import com.alibaba.fastjson.JSON;
import com.k.ums.model.ResponseResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 用来解决认证过的用户访问无权限资源时的异常
 * @Author: kt
 * @CreateTime: 2022/1/26
 */
@Component
public class UmsAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
            throws IOException, ServletException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        String msg = JSON.toJSONString(ResponseResult.error("无法访问资源,请确认已授权"));
        response.getWriter().write(msg);
    }
}
